package jt.classic.app.dbtx;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jt.classic.app.util.DateTool;
import jt.classic.system.ISystem;
import jt.classic.system.database.SystemDataSource;
import net.sf.json.JSONObject;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.limp.basework.SimpleBean;
import org.limp.basework.impl.CommonBean4HSQ;
import org.limp.basework.impl.SimpleBeanImpl;
import org.limp.basework.tools.BaseworkUtil;
import org.limp.mine.Controller;
import org.limp.mine.DataTrimmer;
import org.limp.mine.DateTrimmer;
import org.limp.mine.Label;
import org.limp.mine.QueryJack;
import org.limp.mine.QueryJackFactory;
import org.limp.mine.StringTool;
import org.limp.mine.XMLTool;

public class DbtxAction extends DispatchAction {
    /**
     * 获取指定待办提醒的列表数据
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @throws Exception
     */
    public ActionForward list(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        // String pageNO = StringTool.checkString(param.get("start"));
        String pageNO = StringTool.checkString(param.get("pageNO"));
        String limit = StringTool.checkString(param.get("limit"));

        String type = request.getParameter("type");
        request.setAttribute("type", type);

        StringBuffer where = new StringBuffer(" WHERE 1=1 ");

        Map user = (Map) ISystem.getSessionObject(request, "SHUIWU_USER");

        if (!"".equals(type) && !"null".equals(type) && (type != null)) {
            where.append(" AND TYPE = '" + type + "' ");
        }

        where.append(" AND CREATORID = '" + (String) user.get("userId") + "'");

        String sql1 = "SELECT COUNT(ID) FROM app_dbtx " + where.toString();
        String sql2 = "SELECT * FROM app_dbtx " + where.toString() +
            " ORDER BY REMINDTIME DESC";

        String url = jt.classic.system.ISystem.getContextPath() +
            "/inner/app/dbtx.do?method=list&type=" + type;

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            QueryJack plus = QueryJackFactory.getInstance()
                                             .createQueryJack(false);

            // 设置
            plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
            plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
            plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
            plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, url);
            plus.setParameter(QueryJackFactory.PAGINATION_COUNT, limit);
            plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

            // plus.setParameter(QueryJackFactory.PAGINATION_UPDATEPAGENO, "");
            List resultList = plus.work();

            if ((resultList != null) && !resultList.isEmpty()) {
                DbtxManager manger = new DbtxManager(conn);

                for (int i = 0; i < resultList.size(); i++) {
                    Map info = (Map) resultList.get(i);
                    String id = (String) info.get("ID");

                    Map prop = manger.getDbtxPropById(id);

                    info.put("PROP", prop);
                }
            }

            Controller controller = plus.getController("form1");

            controller.setType("input");

            Label label = plus.getLabel();

            label.setType("href");

            Object[] result = new Object[4];
            result[0] = resultList;
            result[1] = label;
            result[2] = controller;
            result[3] = pageNO;

            /*
             * ListRange lr = new ListRange();
             * lr.setTotalSize(label.totaldata()); lr.setList(resultList);
             * lr.setSuccess(true); outJson(lr, response);
             */
            request.setAttribute("result", result);
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("morelist");
    }

    /**
     * 获取日程信息列表
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @throws Exception
     */
    public ActionForward calendarlist(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        // String pageNO = StringTool.checkString(param.get("start"));
        String pageNO = StringTool.checkString(param.get("pageNO"));
        String limit = StringTool.checkString(param.get("limit"), "10");
        String date = StringTool.checkString(param.get("date"), "-1");

        StringBuffer where = new StringBuffer(" WHERE 1=1 ");

        Map user = (Map) ISystem.getSessionObject(request, "SHUIWU_USER");

        where.append(" AND CREATORID = '" + (String) user.get("userId") + "'");

        where.append(" AND REMINDTIME LIKE '%" + date + "%'");

        request.setAttribute("date", DateTrimmer.getYMD_LBL(date));

        String sql1 = "SELECT COUNT(ID) FROM app_dbtx " + where.toString();
        String sql2 = "SELECT ID FROM app_dbtx " + where.toString() +
            " ORDER BY STIME";

        String url = jt.classic.system.ISystem.getContextPath() +
            "/inner/app/dbtx.do?method=calendarlist&date=" + date;

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            QueryJack plus = QueryJackFactory.getInstance()
                                             .createQueryJack(false);

            // 设置
            plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
            plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
            plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
            plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, url);
            plus.setParameter(QueryJackFactory.PAGINATION_COUNT, limit);
            plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

            // plus.setParameter(QueryJackFactory.PAGINATION_UPDATEPAGENO, "");
            List resultList = plus.work();

            if ((resultList != null) && !resultList.isEmpty()) {
                DbtxManager manager = new DbtxManager(conn);

                for (int i = 0; i < resultList.size(); i++) {
                    Map info = (Map) resultList.get(i);
                    String id = (String) info.get("ID");
                    String num = (String) info.get("PAGINATION_NUMBER");

                    Map baseInfo = manager.getDbtxById(id);

                    Map prop = manager.getDbtxPropById(id);

                    if (prop != null) {
                        baseInfo.putAll(prop);
                    }

                    baseInfo.put("PAGINATION_NUMBER", num);

                    resultList.set(i, baseInfo);
                }
            }

            Controller controller = plus.getController("form1");

            controller.setType("input");

            Label label = plus.getLabel();

            label.setType("href");

            Object[] result = new Object[4];
            result[0] = resultList;
            result[1] = label;
            result[2] = controller;
            result[3] = pageNO;

            /*
             * ListRange lr = new ListRange();
             * lr.setTotalSize(label.totaldata()); lr.setList(resultList);
             * lr.setSuccess(true); outJson(lr, response);
             */
            request.setAttribute("result", result);
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("calendarlist");
    }


    /**
     * 个人日程日历
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward calendar(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;
        ActionForward forward = null;


        String startDate = StringTool.checkString(request.getParameter(
                    "startDate"),
                DateTrimmer.formatDateForVarchar(DateTrimmer.getMonthFirstDay()) +
                "000000");

        String endDate = StringTool.checkString(request.getParameter("endDate"),
                DateTrimmer.formatDateForVarchar(DateTrimmer.getMonthLastDay()) +
                "235959");

        /*String startDate = DateTrimmer.formatDateForVarchar(DateTrimmer.getMonthFirstDay() + "000000");
        
        String endDate = DateTrimmer.formatDateForVarchar(DateTrimmer.getMonthLastDay() + "235959");*/

        /*当前显示日历日期格式化*/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");

        /*当前显示日期*/
        Date nowDate = sdf.parse(startDate);

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(nowDate);

        /*当前日期所在年*/
        String year = String.valueOf(calendar.get(Calendar.YEAR));

        /*当前日期所在月*/
        String month = String.valueOf(calendar.get(Calendar.MONTH));

        /*返回到页面用于初始化日历年显示*/
        request.setAttribute("year", year);

        /*返回到页面用于初始华日历月显示*/
        request.setAttribute("month", month);

        /*日程开始日期(用于删除时传递参数)*/
        request.setAttribute("startDate", startDate);

        /*日程结束日期(用于删除时传递参数)*/
        request.setAttribute("endDate", endDate);

        /* Date date = new Date();
        
         Calendar calendar = Calendar.getInstance();
        
        
         calendar.setTime(date)*/
        long sdate = Long.parseLong(DateTrimmer.formatDateForVarchar(
                    DateTrimmer.getMonthFirstDay()));

        long edate = Long.parseLong(DateTrimmer.formatDateForVarchar(
                    DateTrimmer.getMonthLastDay()));

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            DataTrimmer trimmer = new DataTrimmer(conn);

            Map calendarMap = new HashMap();

            for (long i = sdate; i <= edate; i++) {
                String tDate = String.valueOf(i);

                int idx = DateTool.getWeekIndex(DateTrimmer.getYMD_LBL(tDate));

                String sql = "SELECT ID,TITLE,TYPE,CREATETIME,STIME,ETIME FROM APP_DBTX WHERE STIME <= '" +
                    i + "595959' AND ETIME >= '" + i + "000000'";

                if ((idx == 6) || (idx == 7)) {
                    sql += " AND ICWE = 1";
                }

                sql += " ORDER BY STIME";

                List list = trimmer.searchMultiData(sql);

                if (!list.isEmpty()) {
                    calendarMap.put(DateTrimmer.getYMD_LBL(tDate), list);
                }
            }

            request.setAttribute("calendarMap", calendarMap);

            forward = mapping.findForward("calendar");
        } catch (Exception ex) {
            forward = mapping.findForward("error");
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return forward;
    }

    /**
     * 个人日程日历
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward savecalendar(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;
        ActionForward forward = null;

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            CommonBean4HSQ cbh = new CommonBean4HSQ(request);

            Map param = cbh.getResource();

            BaseworkUtil util = new BaseworkUtil();
            Map result = (Map) util.manualRemix("APP_DBTX", request, conn);

            String id = (String) result.get("ID");

            util.manualDelete("APP_DBTX_PROP", request, conn);

            String sdate = (String) param.get("sdate");
            SimpleBean sbprop = new SimpleBeanImpl();
            sbprop.getResource().put("pname", "sdate");
            sbprop.getResource().put("pvalue", sdate);
            sbprop.getResource().put("id", id);
            util.manualSave("APP_DBTX_PROP", sbprop, conn);

            String stime = (String) param.get("stime");
            sbprop.getResource().clear();
            sbprop.getResource().put("pname", "stime");
            sbprop.getResource().put("pvalue", stime);
            sbprop.getResource().put("id", id);
            util.manualSave("APP_DBTX_PROP", sbprop, conn);

            String edate = (String) param.get("edate");
            sbprop.getResource().clear();
            sbprop.getResource().put("pname", "edate");
            sbprop.getResource().put("pvalue", edate);
            sbprop.getResource().put("id", id);
            util.manualSave("APP_DBTX_PROP", sbprop, conn);

            String etime = (String) param.get("etime");
            sbprop.getResource().clear();
            sbprop.getResource().put("pname", "etime");
            sbprop.getResource().put("pvalue", etime);
            sbprop.getResource().put("id", id);
            util.manualSave("APP_DBTX_PROP", sbprop, conn);

            String tx = StringTool.checkString(param.get("tx"));

            sbprop.getResource().clear();
            sbprop.getResource().put("pname", "tx");
            sbprop.getResource().put("pvalue", tx);
            sbprop.getResource().put("id", id);
            util.manualSave("APP_DBTX_PROP", sbprop, conn);

            if (tx.equals("yes")) {
                String txdate = (String) param.get("txdate");
                sbprop.getResource().clear();
                sbprop.getResource().put("pname", "txdate");
                sbprop.getResource().put("pvalue", txdate);
                sbprop.getResource().put("id", id);
                util.manualSave("APP_DBTX_PROP", sbprop, conn);

                String txtime = (String) param.get("txtime");
                sbprop.getResource().clear();
                sbprop.getResource().put("pname", "txtime");
                sbprop.getResource().put("pvalue", txtime);
                sbprop.getResource().put("id", id);
                util.manualSave("APP_DBTX_PROP", sbprop, conn);

                String txmessage = StringTool.checkString(param.get("txmessage"));

                if (txmessage.equals("1")) {
                    sbprop.getResource().clear();
                    sbprop.getResource().put("pname", "txmessage");
                    sbprop.getResource().put("pvalue", txmessage);
                    sbprop.getResource().put("id", id);
                    util.manualSave("APP_DBTX_PROP", sbprop, conn);
                }
            }

            conn.commit();

            String url = "/dbtx.do?method=calendar";

            forward = new ActionForward();
            forward.setPath(url);

            forward.setRedirect(true);
        } catch (Exception ex) {
            conn.rollback();
            forward = mapping.findForward("error");
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return forward;
    }

    /**
     * 编辑个人日程信息
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward editcalendar(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;
        Map info = null;

        String id = StringTool.checkString(request.getParameter("id"));

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            String sql = "SELECT * FROM APP_DBTX WHERE ID = " + id;

            DataTrimmer trimmer = new DataTrimmer(conn);

            info = trimmer.searchSingleData(sql);

            if (info != null) {
                sql = "SELECT * FROM APP_DBTX_PROP WHERE ID = " + id;

                Map prop = trimmer.searchSymmetricalData(sql, "PNAME", "PVALUE");

                if (prop != null) {
                    info.putAll(prop);
                }
            }
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        String result = XMLTool.result2XML(info);
        request.setAttribute("result", result);

        return mapping.findForward("result");
    }

    /**
     * 个人日程日历
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward deletecalendar(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;
        ActionForward forward = null;

        String startDate = StringTool.checkString(request.getParameter(
                    "startDate"),
                DateTrimmer.formatDateForVarchar(DateTrimmer.getMonthFirstDay()) +
                "000000");

        String endDate = StringTool.checkString(request.getParameter("endDate"),
                DateTrimmer.formatDateForVarchar(DateTrimmer.getMonthLastDay()) +
                "235959");

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            BaseworkUtil util = new BaseworkUtil();
            util.manualDelete("APP_DBTX", request, conn);
            util.manualDelete("APP_DBTX_PROP", request, conn);

            conn.commit();

            String url = "/dbtx.do?method=calendar&startDate=" + startDate +
                "&endDate=" + endDate;

            forward = new ActionForward();
            forward.setPath(url);

            forward.setRedirect(true);
        } catch (Exception ex) {
            forward = mapping.findForward("error");
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return forward;
    }

    /**
     * 获取html格式的待办提醒列表数据
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @throws Exception
     */
    public static String htmlList(String type, int size, String userId)
        throws Exception {
        Connection conn = null;

        if (size <= 0) {
            size = 10;
        }

        StringBuffer sb = new StringBuffer("");

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            DbtxManager dm = new DbtxManager(conn);
            List resultList = dm.getDbtxByType(type, size, userId);

            if ((resultList != null) && !resultList.isEmpty()) {
                if ("hytx".equals(type)) {
                    sb.append("<tr>");
                    sb.append(
                        "<td width=\"20%\" class=\"hytxtd\" align=\"center\">时 间</td>");
                    sb.append(
                        "<td width=\"30%\" class=\"hytxtd\" align=\"center\">地 点</td>");
                    sb.append(
                        "<td width=\"50%\" class=\"hytxtd\">&nbsp;内 容</td>");
                    sb.append("</tr>");
                }

                for (int i = 0; i < resultList.size(); i++) {
                    Map m = (Map) resultList.get(i);
                    String id = (String) m.get("ID");
                    String title = (String) m.get("TITLE");
                    String url = (String) m.get("URL");
                    String rtime = DateTrimmer.getYMD_LBL((String) m.get(
                                "REMINDTIME"));

                    if ("hytx".equals(type)) {
                        Map prop = dm.getDbtxPropById(id);

                        sb.append("<tr><td align=\"center\">" +
                            prop.get("time") + "</td>");
                        sb.append("<td align=\"center\">" +
                            prop.get("address") + "</td>");

                        if ("".equals(url) || (url == null)) {
                            sb.append("<td><a href=\"#\" >" + title +
                                "</a></td></tr>");
                        } else {
                            sb.append("<td><a href=\"" + url +
                                "\"  target=\"_blank\">" + title +
                                "</a></td></tr>");
                        }
                    } else {
                        if ("".equals(url) || (url == null)) {
                            sb.append("<tr><td><a href=\"#\" >" + title +
                                "</a></td>");
                        } else {
                            sb.append("<tr><td><a href=\"" + url +
                                "\"  target=\"_blank\">" + title + "</a></td>");
                        }

                        sb.append("<td width=70>" + rtime + "</td></tr>");
                    }
                }
            }
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return sb.toString();
    }

    public void outJsonString(String str, HttpServletResponse response) {
        response.setContentType("text/javascript;charset=UTF-8");
        outString(str, response);
    }

    public void outJson(Object obj, HttpServletResponse response) {
        outJsonString(JSONObject.fromObject(obj).toString(), response);
    }

    public void outString(String str, HttpServletResponse response) {
        try {
            PrintWriter out = response.getWriter();

            // System.out.println(str);
            out.write(str);
        } catch (IOException e) {
        }
    }
}
